package com.mojo.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理代码示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/4 10:46
 */
public class DynamicProxy {
    public static void main(String[] args) {
        MyProxy proxy = new MyProxy();
        Inter inter = (Inter) proxy.getInstance(new Impl());
        inter.m();
    }
}

interface Inter {
    void m();
}

class Impl implements Inter {

    @Override
    public void m() {
        System.out.println("真实对象。。。");
    }
}

class MyProxy implements InvocationHandler {
    private Object obj;

    public Object getInstance(Object o) {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), o.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理增强");
        //实际执行
        method.invoke(proxy);
        return null;
    }
}